<template>
    <div class="result">
        <!-- :style="{ display: ['IN_CALCULATE', 'CALULATE_FINISH'].includes(state.process.staticDataState.state) ? '' : 'none' }" -->
        <div class="left-chart">
            <div class="progressStyle">
                <el-tooltip placement="top">
                    <div slot="content">
                        <div style="margin-left: 12px">
                            <ul>
                                <li>
                                    <span>总数：{{ state.process.totalAmount }}</span>
                                </li>
                                <li class="second">
                                    <span>成功：{{ state.process.successAmount }}</span>
                                </li>
                                <li class="third">
                                    <span>失败：{{ state.process.errorAmount }}</span>
                                </li>
                                <li class="fourth">
                                    <span>过滤{{ state.process.filterAmount }}</span>
                                </li>
                            </ul>
                        </div>
                    </div>
                    <el-progress
                        type="circle"
                        :class="{ progress_bor: state.process.staticDataState.state == 'CALULATE_FINISH' }"
                        :percentage="
                            state.process.totalAmount - state.process.filterAmount
                                ? ((state.process.successAmount + state.process.errorAmount) * 100) /
                                  (state.process.totalAmount - state.process.filterAmount)
                                : 0
                        "
                        :stroke-width="10"
                        :width="120"
                        :format="formatProgress"
                    >
                    </el-progress>
                </el-tooltip>
            </div>
            <div ref="leftChart" id="leftChart" style="height: calc(100% - 120px); min-height: 170px"></div>
        </div>
        <div class="right-chart">
            <div style="display: flex">
                <span style="color: black; line-height: 28px">筛选基金：</span>
                <risk-custom-select
                    :selectKeys="selectKey"
                    :dataSource="name.fundInfo"
                    :showSearch="true"
                    :showSelectAll="true"
                    @customSelectReturn="customSelectReturn"
                    :key="filterNumKey + 'filterNumKey'"
                ></risk-custom-select>
            </div>
            <div ref="rightChart" id="rightChart" style="height: calc(100% - 30px); min-height: 300px"></div>
        </div>
    </div>
</template>
<script lang="ts">
import { Component, Vue, Prop, Watch } from 'vue-property-decorator';
import * as ECharts from 'echarts';
import DictionConstUtil from '@/utils/diction-const-util';
import RiskCustomSelect from '@/common/components/risk-custom-select.vue';
@Component({
    name: 'ProcessChart',
    components: {
        RiskCustomSelect,
    },
})
export default class ProcessChart extends Vue {
    @Prop() state;
    @Prop() renderCount: number;

    // state = {
    //     process: {
    //         totalAmount: 312,
    //         successAmount: 200,
    //         errorAmount: 100,
    //         filterAmount: 12,
    //         warning: [10],
    //         examine: [30],
    //         prohibit: [20],
    //         error: [10],
    //         compliance: [30],
    //     },
    //     selectKey: [],
    //     data: {
    //         lengthGx: 1,
    //         xAxios: [1, 2, 3, 4, 5, 6, 7, 8, 10, 11],
    //         compliance: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    //         warning: [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    //         examine: [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    //         prohibit: [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    //         error: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    //     },
    //     xScale: 32, // X轴刻度数
    //     pStart: 0,
    //     pEnd: 3,
    // };

    // 筛选基金
    private selectKey: any = [];

    private data = {
        lengthGx: 1,
        // xAxios: [1, 2, 3, 4, 5, 6, 7, 8, 10, 11],
        // compliance: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        // warning: [2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        // examine: [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        // prohibit: [3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        // error: [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
        xAxios: [],
        compliance: [],
        warning: [],
        examine: [],
        prohibit: [],
        error: [],
    };
    // X轴刻度数
    private xScale: number = 32;
    private pStart: number = 0;
    private pEnd: number = 3;
    private name = {
        fundInfo: [],
        renderCount: 1,
        selectKeysCache: [],
    };

    private filterNumKey: number = -1;

    // // 转为监听父子通信值
    // @Watch('state')
    // receiveProps() {
    //     if (this.state.process.renderCount !== this.name.renderCount) {
    //         this.name.renderCount = this.state.process.renderCount;
    //         this.data = this.handelFiter(this.selectKey, this.state.process);
    //     }
    // }

    /**
     * 监听消息变动 重新渲染 图表数据更新
     */
    @Watch('renderCount', { immediate: true })
    watchRenderCount(newData) {
        console.log('监听消息变动 重新渲染 图表数据更新', newData, '!');
        this.$nextTick(async () => {
            this.updateChartL();

            if (!this.name.fundInfo.length) {
                let funds = await DictionConstUtil.FNFundInfo();
                let fundInfo = funds.map(item => {
                    return { dictKey: item.fundCode, dictKeyName: item.fundName, showCode: item.showCode };
                });
                this.name.fundInfo = fundInfo.sort((a, b) => a.dictKey.replace(/[^0-9]/gi, '') - b.dictKey.replace(/[^0-9]/gi, ''));
            }

            let handelFiter = this.handelFiter(this.selectKey, this.state.process);
            let scrolLeng = 2000 / handelFiter.lengthGx;
            scrolLeng = scrolLeng > 100 ? 100 : scrolLeng;
            this.data = handelFiter;
            this.pStart = 0;
            this.pEnd = scrolLeng;
            this.updateChartR();

            this.filterNumKey++;
        });
    }

    chartInstanceL: any = null; // 左图表实例
    chartInstanceR: any = null; // 右图表实例

    async mounted() {
        console.error('mounted', JSON.parse(JSON.stringify(this.state)));
        this.initChartL();
        this.initChartR();
    }

    dispose() {
        this.chartInstanceL.dispose(); // 销毁实例
        this.chartInstanceR.dispose(); // 销毁实例
        this.initChartL();
        this.initChartR();
    }

    beforeDestroy() {
        this.chartInstanceL.clear();
        this.chartInstanceR.clear();
        this.chartInstanceL.dispose();
        this.chartInstanceR.dispose();
        this.chartInstanceL = null;
        this.chartInstanceR = null;
    }

    initChartL() {
        this.chartInstanceL = ECharts.init(this.$refs.leftChart);
        const initOption = {
            tooltip: {
                trigger: 'axis',
                formatter: params => {
                    let value = params.find(item => item.data !== 0);
                    if (value) {
                        return value.name + ':' + value.data;
                    } else {
                        return '';
                    }
                },
            },
            axisPointer: {
                // 坐标轴指示器，坐标轴触发有效
                type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
            },
            legend: {
                data: ['合规', '警告', '送审', '禁止', '错误'],
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '3%',
                containLabel: true,
            },
            xAxis: {
                type: 'value',
                // max: (value) => value.max + 10,
                splitNumber: 3,
                minInterval: 1,
                axisLabel: {
                    rotate: 40,
                },
            },
            yAxis: {
                type: 'category',
                data: ['合规', '警告', '送审', '禁止', '错误'],
            },
            color: ['#87D068', '#FFA500', '#CD5C5C', '#D53A35', '#334B5C'],
        };
        this.chartInstanceL.setOption(initOption);
    }

    initChartR(): void {
        this.chartInstanceR = ECharts.init(this.$refs.rightChart);
        const initOption = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    // 坐标轴指示器，坐标轴触发有效
                    type: 'shadow', // 默认为直线，可选为：'line' | 'shadow'
                },
            },
            xAxis: {
                type: 'category',
                // data: [],
                axisLabel: {
                    interval: 0,
                    rotate: 40,
                    formatter: function(value, index) {
                        return value.split(' ')[0];
                    },
                },
            },
            legend: {
                top: 10,
                left: 10,
                data: ['合规数量', '警告数量', '送审数量', '禁止数量', '错误数量'],
            },
            grid: {
                left: '0%',
                right: '0%',
                bottom: '10%',
                containLabel: true,
            },
            yAxis: {
                type: 'value',
                max: function(value) {
                    return value.max + 10;
                },
            },
            color: ['#87D068', '#FFA500', '#CD5C5C', '#D53A35', '#334B5C'],
        };
        this.chartInstanceR.setOption(initOption);
        console.log('R初始化完成');
    }

    updateChartL() {
        console.log('图表接收数据 updateChartL:', this.state.process);

        let series = [
            {
                name: '合规',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: false,
                        formatter: param => (param.data === 0 ? '' : param.data),
                        position: 'insideRight',
                    },
                },
                data: [this.state.process.compliance, 0, 0, 0, 0],
            },
            {
                name: '警告',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: false,
                        formatter: param => (param.data === 0 ? '' : param.data),
                        position: 'insideRight',
                    },
                },
                data: [0, this.state.process.warning, 0, 0, 0],
            },
            {
                name: '送审',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: false,
                        formatter: param => (param.data === 0 ? '' : param.data),
                        position: 'insideRight',
                    },
                },
                data: [0, 0, this.state.process.examine, 0, 0],
            },
            {
                name: '禁止',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: false,
                        formatter: param => (param.data === 0 ? '' : param.data),
                        position: 'insideRight',
                    },
                },
                data: [0, 0, 0, this.state.process.prohibit, 0],
            },
            {
                name: '错误',
                type: 'bar',
                stack: '总量',
                label: {
                    normal: {
                        show: false,
                        formatter: param => (param.data === 0 ? '' : param.data),
                        position: 'insideRight',
                    },
                },
                data: [0, 0, 0, 0, this.state.process.error],
            },
        ];
        const dataOption = { series };
        this.chartInstanceL.setOption(dataOption);
    }

    updateChartR() {
        console.log('图表接收数据 updateChartR:', this.data);

        const dataOption = {
            xAxis: {
                type: 'category',
                data: this.data.xAxios,
                axisLabel: {
                    interval: 0,
                    rotate: 40,
                    formatter: function(value, index) {
                        return value.split(' ')[0];
                    },
                },
            },
            dataZoom: [
                {
                    type: 'slider',
                    show: true,
                    xAxisIndex: [0],
                    start: this.pStart,
                    end: this.pEnd,
                    zoomLock: false,
                },
                {
                    type: 'inside',
                    xAxisIndex: [0],
                    start: this.pStart,
                    end: this.pEnd,
                    zoomLock: false,
                },
            ],
            series: [
                {
                    name: '合规数量',
                    type: 'bar',
                    stack: '总量',
                    label: {
                        normal: {
                            show: true,
                            formatter: param => (param.data === 0 ? '' : param.data),
                        },
                    },
                    data: this.data.compliance,
                },
                {
                    name: '警告数量',
                    type: 'bar',
                    stack: '总量',
                    label: {
                        normal: {
                            show: true,
                            formatter: param => (param.data === 0 ? '' : param.data),
                        },
                    },
                    data: this.data.warning,
                },
                {
                    name: '送审数量',
                    type: 'bar',
                    stack: '总量',
                    label: {
                        normal: {
                            show: true,
                            formatter: param => (param.data === 0 ? '' : param.data),
                        },
                    },
                    data: this.data.examine,
                },
                {
                    name: '禁止数量',
                    type: 'bar',
                    stack: '总量',
                    label: {
                        normal: {
                            show: true,
                            formatter: param => (param.data === 0 ? '' : param.data),
                        },
                    },
                    data: this.data.prohibit,
                },
                {
                    name: '错误数量',
                    type: 'bar',
                    stack: '总量',
                    label: {
                        normal: {
                            show: true,
                            formatter: param => (param.data === 0 ? '' : param.data),
                        },
                    },
                    data: this.data.error,
                },
            ],
        };
        this.chartInstanceR.setOption(dataOption);
    }

    // 格式计算进度
    private formatProgress(percent: number): string {
        return (window.isNaN(percent) ? 0 : percent.toFixed(2)) + '%' + '\n' + '计算进度';
        // return `${percent}% 还剩 15 天`;
    }

    // 右下角图形
    handelFiter(filterKey: any, process: any) {
        let data = {
            lengthGx: 1,
            xAxios: [],
            compliance: [],
            warning: [],
            examine: [],
            prohibit: [],
            error: [],
        };
        let staticFundResult = process['staticFundResult'] || {};
        let fundInfo = this.name.fundInfo;

        let xAxios = fundInfo.filter(item =>
            filterKey && filterKey.length > 0 && !filterKey.includes('-1') ? filterKey.includes(item.dictKey) : true
        );
        for (let value of xAxios) {
            let fundDetail = staticFundResult[value.dictKey];
            if (fundDetail) {
                data.xAxios.push(value.dictKey + ' ' + value.dictKeyName);
                data.compliance.push(fundDetail.compliance);
                data.warning.push(fundDetail.warning);
                data.examine.push(fundDetail.examine);
                data.prohibit.push(fundDetail.prohibit);
                data.error.push(fundDetail.error);
            } else {
                data.xAxios.push(value.dictKey + ' ' + value.dictKeyName);
                data.compliance.push(0);
                data.warning.push(0);
                data.examine.push(0);
                data.prohibit.push(0);
                data.error.push(0);
            }
        }
        let lg = data.xAxios.length;
        if (lg < this.xScale) {
            for (let i = 0; i < this.xScale - lg; i++) {
                data.xAxios.push('-');
                data.compliance.push(0);
                data.warning.push(0);
                data.examine.push(0);
                data.prohibit.push(0);
                data.error.push(0);
            }
        }
        data.lengthGx = data.xAxios.length;
        return data;
    }

    // 基金参数变动
    private handleBaseInfo(selectKey: any): void {
        if (selectKey === ['-1']) {
            selectKey = this.name.fundInfo;
        }
        selectKey = selectKey || [];
        if (selectKey.length === this.name.selectKeysCache.length) {
            if (selectKey.length === 0 || selectKey.every(item => this.name.selectKeysCache.includes(item))) {
                return;
            }
        }
        this.name.selectKeysCache = JSON.parse(JSON.stringify(selectKey));
        let handelFiter = this.handelFiter(selectKey, this.state.process);
        let scrolLeng = 2000 / handelFiter.lengthGx;
        scrolLeng = scrolLeng > 100 ? 100 : scrolLeng;
        this.data = handelFiter;
        this.pStart = 0;
        this.pEnd = scrolLeng;
        this.updateChartR();
    }

    // 筛选基金下拉框返回值
    private customSelectReturn(keys: any): void {
        this.handleBaseInfo(keys);
    }

    // // 图标滚动事件
    // private proToc = null;

    // private handeDataZoom(param, e): void {
    //     if (this.proToc) {
    //         clearTimeout(this.proToc);
    //         this.proToc = null;
    //     }
    //     this.proToc = setTimeout(() => {
    //         let start = param.start || param.start === 0 ? param.start : this.pStart;
    //         let end = param.end || param.end === 0 ? param.end : this.pEnd;
    //         this.pStart = start;
    //         this.pEnd = end;
    //     }, 1000);
    // }
}
</script>
<style lang="scss" scoped>
.result {
    padding: 10px;
    overflow: hidden;
    height: calc(55% - 70px);
    min-height: 350px;
    display: flex;
    p {
        font-size: 18px;
        margin-top: 30px;
    }
    .left-chart {
        height: 100%;
        width: 350px;
        .progressStyle {
            height: 120px;
            text-align: center;
        }
    }

    .right-chart {
        height: 100%;
        margin-left: 20px;
        flex: 1;
        width: calc(100% - 350px);
    }
}
/deep/ .el-progress--circle .el-progress__text {
    font-weight: 900;
    white-space: pre-wrap;
}
.second {
    list-style-type: disc;
    color: green;
}
.third {
    list-style-type: disc;
    color: red;
}
.fourth {
    list-style-type: disc;
    color: yellow;
}
span {
    color: #fff;
}

.progress_bor /deep/ .el-progress-circle {
    height: 120px !important;
    width: 120px !important;
}
.progress_bor /deep/ .el-progress-circle svg > path:nth-child(2) {
    stroke: rgb(135, 208, 104);
}
</style>
